class VideosController < ApplicationController
  layout "home"
  
  # GET /videos
  # GET /videos.xml
  def index
    #@videos = Video.all
    @event=Event.all
    @video_status=VideoStatus.all
    @users=User.all
    @filter = params[:filter].nil? ? {} : params[:filter]
    @page = params[:page].nil? ? 1 : params[:page]
    #@videos = Video.all.paginate :page=>params[:page], :order=>'created_at desc', :per_page => 2
    #@videos = Video.all.paginate :page=>(params[:page].to_i - 1), :order=>'created_at desc', :per_page => 3 if @videos.count == 0 && !params[:page].nil?
    @videos =  Video.filter(@filter).paginate :page=>params[:page], :per_page => 3
    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @videos }
    end
  end
  
  def thumbnail
    @video = Video.find(params[:id])
    
    send_file @video.renderThumbnail,
				  :filename => @video.thumbnail, 
                                  :type => "image/JPG",
                                  :disposition => 'inline'
  end
  
  def thumbnail75
    @video = Video.find(params[:id])
    
    send_file @video.renderThumbnail75,
				  :filename => @video.thumbnail, 
                                  :type => "image/JPG",
                                  :disposition => 'inline'
  end

  # GET /videos/1
  # GET /videos/1.xml
  def show    
    @video = Video.find(params[:id])
    
    #response.headers['Content-Type'] = "application/force-download"
    #response.headers['Content-Disposition'] = "attachment; filename=\"#{File.basename(@video.path)}\"" 
    #response.headers["X-Sendfile"] = @video.path
    # response.headers['Content-length'] = File.size(@video.path)
    
    send_file @video.renderVideo,
				  :filename => @video.path, 
                                  :type => "video/#{@video.video_type}",
                                  :disposition => 'inline', :x_sendfile=>true
  end
  
  def file
    @video = Video.find(params[:id])
    
    send_file @video.renderVideo,
				  :filename => @video.path, 
                                  :type => "video/mp4",
                                  :disposition => 'inline', :x_sendfile=>true
  end
  
  def details
    @video = Video.find(params[:id])
    @popular = Video.find(:all, :order => "created_at")
    @channels = Channel.find(:all, :order => "title")
    @user = current_user
  end

  # GET /videos/new
  # GET /videos/new.xml
  def new
    @video = Video.new
    @event = Event.all
     @video_statuses = VideoStatus.all
    respond_to do |format|
      format.html # new.html.erb
      format.xml  { render :xml => @video }
    end
  end

  # GET /videos/1/edit
  def edit
    @video = Video.find(params[:id])
    @event=Event.all
    @video_statuses = VideoStatus.all
  end

  # POST /videos
  # POST /videos.xml
  def create
    @video = Video.new(params[:video])

     #Get value
        obj=params[:upload][:datafile]
        #Lay ten video tren text
        filename=params[:video][:title]
        
        name = obj.original_filename
        directory = "public/videos"
        
        #Duong dan cua file
        path_file=File.join(directory,name)
        
        #Lay ten mo rong cua file
        extend_file=File.extname(path_file)
        
    respond_to do |format|
      if @video.save
         #Save to database
        #@video.title = @video.id.to_s + '_' + name if @video.title.empty? || @video.title.nil?
        if filename.empty? || filename.nil?
          @video.title = @video.id.to_s + '_' + name
        else
          @video.title = @video.id.to_s + '_'+ filename + extend_file
        end
        @video.save
        
        #Upload
        name=@video.title
        
        
         #tao duong dan luu vao csdl
        path=File.join(directory,name)
        
        #Update path of video
        @video.path=path
        @video.save
        
        #ghi file
        File.open(path,"wb") {|f| f.write(obj.read) }

        format.html { redirect_to(@video, :notice => 'Video was successfully created.') }
        format.xml  { render :xml => @video, :status => :created, :location => @video }
      else
        format.html { render :action => "new" }
        format.xml  { render :xml => @video.errors, :status => :unprocessable_entity }
      end
    end
  end

  # PUT /videos/1
  # PUT /videos/1.xml
  def update
    @video = Video.find(params[:id])
    @video_statuses = VideoStatus.all
    
    respond_to do |format|
      if @video.update_attributes(params[:video])
        format.html { redirect_to(@video, :notice => 'Video was successfully updated.') }
        format.xml  { head :ok }
      else
        format.html { render :action => "edit" }
        format.xml  { render :xml => @video.errors, :status => :unprocessable_entity }
      end
    end
  end

  # DELETE /videos/1
  # DELETE /videos/1.xml
  def destroy
    @video = Video.find(params[:id])
    @id_video=@video.id
    Dir.foreach("public/videos"){|x| File.delete("public/videos/"+x) if x=~/^#{@id_video}(.*)/ }
    @video.destroy
   
    respond_to do |format|
      format.html { redirect_to(videos_url) }
      format.xml  { head :ok }
    end
  end
  
  def search_video
    @bien=params[:txtText]
    @bien1=params[:Video]
    @bien1=@bien1[:event_id]
    @bienngay=params[:start_date]
    @video = Video.all
    @event=Event.all
    @video_status=VideoStatus.all
  
    # @article = Article.where("title like '%'")
    @videos =  Video.where(" title like '%#{@bien}%' and event_id = '#{@bien1}' ")#and start_publishing = '#{@bienngay}'")
     respond_to do |format|
       #redirect_to :action =>'index'
      format.html {render 'index.html.erb'}
      #format.xml  { render :xml => @article }
    end
  end
  
  def delete_selected
    @ids = params[:ids]
    @user = current_user
    @ids.each do |obj|
      @video = Video.find(obj[0])
      @id_video=@video.id
      Dir.foreach("public/videos"){|x| File.delete("public/videos/"+x) if x=~/^#{@id_video}(.*)/ }
      @video.destroy
    end
    
    respond_to do |format|
        format.html { redirect_to(videos_url, :notice => "Video was successfully deleted.") }
        format.xml  { head :ok }
        #format.js { render 'destroy.js.erb' }
    end
  end
  
  def approve
    begin
      @video = Video.find(params[:id])
    rescue ActiveRecord::RecordNotFound      
      return nil
    end
    
    # right bar
    @videos_approving = Video.videos_approving
    @videos_new = Video.video_new

    respond_to do |format|
      format.html # show.html.erb
      format.xml  { render :xml => @video }
    end
  end
  
  def approving
    @video = Video.find(params[:id])
    @video.video_status = VideoStatus.get('APPROVING')
    
    # add approval history
    @approval = @video.video_approvals.create(:status => @video.video_status.name, :user_id => current_user.id)
    
    respond_to do |format|
        if @video.update_attributes(params[:video])
          format.html { redirect_to({:controller => 'videos'}, :notice => "Video '#{@video.title}' was in approving list.") }
          format.xml  { head :ok }
        else
          format.html { redirect_to({:controller => 'videos'}, :notice => "Can't move article to approving list.") }
          format.xml  { render :xml => @video.errors, :status => :unprocessable_entity }
        end
    end
  end
  
  def preview_video
    @video = Video.find(params[:id])
    render :layout => false
  end
end
